package com.gxgeek.redis.application.application.lock;

import com.gxgeek.redis.application.redistool.JedisExecutor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;


/**
 * @author gaoxing
 * @create 2017-09-26 下午7:14
 */
@Slf4j
public class RedisLock  {


    /**
     * 加锁
     *
     * @param key
     * @param value 当前时间+超时时间
     * @return
     */
    public boolean lock(String key, String value) {
        if (JedisExecutor.execute(jedis -> jedis.setnx(key, value)) > 0) {
            return true;
        }

        String currentValue = JedisExecutor.execute(jedis -> jedis.get(key));
        //如果锁过期
        if (!StringUtils.isEmpty(currentValue)
                && Long.parseLong(currentValue) < System.currentTimeMillis()) {
            //获取上一个锁的时间
            String oldValue = JedisExecutor.execute(jedis -> jedis.getSet(key, value));
            if (!StringUtils.isEmpty(oldValue) && oldValue.equals(currentValue)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 解锁
     *
     * @param key
     * @param value
     */
    public void unlock(String key, String value) {
        try {
            String currentValue = JedisExecutor.execute(jedis -> jedis.get(key));
            if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)) {
                JedisExecutor.execute(jedis -> jedis.del(key));
            }
        } catch (Exception e) {
            log.error("【redis分布式锁】解锁异常, {}", e);
        }
    }

}
